package com.chatgpt.api.conf;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @author yangjian
 */
@Configuration
public class AppConfig {

  // 设置默认的 JSON 输出策略
  // 自动将驼峰转为下划线
  @Bean
  public ObjectMapper objectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
    return objectMapper;
  }

  // 配置跨域请求
  @Bean
  public CorsFilter corsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();

    // 允许发送Cookie
    config.setAllowCredentials(true);

    // 允许的请求方法，如 GET、POST 等
    config.addAllowedMethod("*");

    // 允许所有域访问，实际应用中建议根据需要设置具体的域
    config.addAllowedOriginPattern("*");

    // 允许的请求头
    config.addAllowedHeader("*");

    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
  }

}
